# Create your views here.
import json

from django.core.files.base import File
from django.db.models.query_utils import Q
from django.http import JsonResponse
from django.views.decorators.csrf import csrf_exempt
from numpy import double

from student.models import *


@csrf_exempt
def register(request):
    ret_dict = {}
    if request.method == 'POST':
        data = json.loads(request.body)
        new_username = data.get('username')
        new_password1 = data.get('password1')
        new_password2 = data.get('password2')
        if Student.objects.filter(name=new_username):
            ret_dict['res'] = 1
            response = JsonResponse(ret_dict)
            return response
        if len(str(new_password1)) < 6 or len(str(new_password1)) > 18:
            ret_dict['res'] = 2
            response = JsonResponse(ret_dict)
            return response
        n = m = x = y = 0
        for i in new_password1:
            if str.isdigit(i):
                n = 1
            elif str.isalpha(i):
                m = 1
            elif str.isspace(i):
                x = 1
            else:
                y = 1
        if n + m + x + y < 2:
            ret_dict['res'] = 2
            return JsonResponse(ret_dict)

        if new_password2 != new_password1:
            ret_dict['res'] = 3
            response = JsonResponse(ret_dict)
            return response
        else:
            request.session['username'] = new_username
            new_student = Student()
            new_student.name = new_username
            new_student.password = new_password1
            try:
                file = open('1.png', 'rb')
                img = File(file)
            except:
                return JsonResponse(ret_dict)
            new_student.image = img
            new_student.buyNum = 0
            new_student.point = 10
            new_student.sex = 0
            new_student.signature = "这个人很懒，什么都没有留下"
            request.session['username'] = new_username
            new_student.save()
            ret_dict['res'] = 4
            response = JsonResponse(ret_dict)
            return response
    else:
        ret_dict['res'] = 5
        response = JsonResponse(ret_dict)
        return response


@csrf_exempt
def login(request):
    ret_dict = {}
    if request.method == 'POST':
        data = json.loads(request.body)
        username = data.get('username')
        password = data.get('password')
        if not Student.objects.filter(name=username):
            ret_dict['res'] = 1
            response = JsonResponse(ret_dict)
            return response
        user = Student.objects.get(name=username)
        if user.password == password:
            request.session['username'] = username
            ret_dict['res'] = 2
            response = JsonResponse(ret_dict)
            return response
        else:
            ret_dict['res'] = 1
            response = JsonResponse(ret_dict)
            return response

    else:
        ret_dict['res'] = 1
        response = JsonResponse(ret_dict)

        return response


@csrf_exempt
def products_information(request):
    res_dict = {}
    if request.method == 'GET':
        for i in range(1, 10):
            productlist = ProductList.objects.filter(type=i).filter(num__gt=0)[:5]
            arr = []
            for j in productlist:
                st = {}
                st['name'] = j.name
                st['price'] = j.price
                st['image'] = 'http://39.104.170.158:8000' + j.image.url
                st['sellerUsername'] = j.seller
                st['id'] = j.id
                arr.append(st)
            res_dict['array%d' % i] = arr
        needlist = NeedList.objects.all()[:5]
        arr = []
        for i in needlist:
            st = {'username': i.username, 'description': i.description}
            st['time'] = i.time
            student = Student.objects.get(name=i.username)
            st['image'] = 'http://39.104.170.158:8000' + student.image.url
            st['id'] = i.id
            arr.append(st)
        res_dict['array10'] = arr
        return JsonResponse(res_dict)
    elif request.method == 'POST':
        request.session.flush()
        ret_dict = {'res': 1}
        return JsonResponse(ret_dict)


# 主页-特定类别页
@csrf_exempt
def products(request):
    res_dict = {}
    if request.method == 'GET':
        try:
            t = request.GET.get('type')
            productlist = ProductList.objects.filter(type=t).filter(num__gt=0)[:20]
            arr = []
            for i in productlist:
                st = {'name': i.name, 'price': i.price, 'image': 'http://39.104.170.158:8000' + i.image.url,
                      'sellerUsername': i.seller, 'id': i.id}
                arr.append(st)

            res_dict['products'] = arr
        except:
            res_dict['res'] = 0
        return JsonResponse(res_dict)
    else:
        res_dict['res'] = 0
        return JsonResponse(res_dict)


# 需求市集
@csrf_exempt
def needMarket(request):
    if request.method == 'GET':
        needs = NeedList.objects.all()[:20]
        arr = []
        for i in needs:
            str = {}
            str['username'] = i.username
            str['description'] = i.description
            str['time'] = i.time
            product = Student.objects.get(name=i.username)
            str['image'] = 'http://39.104.170.158:8000' + product.image.url
            arr.append(str)
        res_dict = {'needs': arr}
        return JsonResponse(res_dict)


@csrf_exempt
def logout(request):
    request.session.flush()
    ret_dict = {'res': 1}
    return JsonResponse(ret_dict)


# 发布商品
@csrf_exempt
def releaseProducts(request):
    ret_dict = {}
    if request.method == 'POST':
        productlist = ProductList()
        img = request.FILES.get('image')
        if img:
            productlist.image = img
            ret_dict['res'] = 1
        else:
            ret_dict['res'] = 0
        img = request.FILES.get('sellerCode')
        if img:
            productlist.sellerCode = img
            ret_dict['res'] = 1
        else:
            ret_dict['res'] = 0

        try:
            t = request.POST.get('type')
            name = request.POST.get('name')
            username = request.session.get('username')
            description = request.POST.get('description')
            price = request.POST.get('price')
            num = request.POST.get('number')
            tap = request.POST.get('timeAndPlace')
            sellerPhone = request.POST.get('sellerPhone')
        except:
            ret_dict['res'] = 0
            return JsonResponse(ret_dict)
        productlist.name = name
        productlist.seller = username
        productlist.price = price
        productlist.num = num
        productlist.description = description
        productlist.timeAndPlace = tap
        productlist.type = t
        productlist.sellerPhone = sellerPhone
        productlist.save()

        ret_dict['res'] = 1
        return JsonResponse(ret_dict)
    else:
        ret_dict = {'res': 0}
        return JsonResponse(ret_dict)


# 发布需求
@csrf_exempt
def releaseNeeds(request):
    ret_dict = {}
    if request.method == "POST":
        try:
            data = json.loads(request.body)
            description = data.get("description")
            name = request.session.get('username')
            time = data.get('time')
        except:
            ret_dict['res'] = 0
            return JsonResponse(ret_dict)
        need = NeedList()
        need.username = name
        need.description = description
        need.time = time
        need.save()
        ret_dict['res'] = 1
        return JsonResponse(ret_dict)
    else:
        ret_dict['res'] = 0
        return JsonResponse(ret_dict)


# 自己写的第二部分
@csrf_exempt
def search(request):
    res_dict = {}
    if request.method == 'GET':
        try:
            keyword = request.GET.get('keyword')

            products = ProductList.objects.filter(Q(name__contains=keyword) | Q(description__contains=keyword)).filter(
                num__gt=0)[:20]
            arr = []
            for j in products:
                st = {'name': j.name, 'price': j.price, 'image': 'http://39.104.170.158:8000' + j.image.url,
                      'sellerUsername': j.seller, 'pid': j.id}
                arr.append(st)
            res_dict['products'] = arr
            res_dict['res'] = 0
            needs = NeedList.objects.filter(description__contains=keyword)[:20]
            arr = []
            for j in needs:
                st = {'name': j.username, 'image': 'http://39.104.170.158:8000' + Student.objects.get(name=j.username).image.url,
                      'description': j.description, 'time': j.time}
                arr.append(st)
            res_dict['needs'] = arr
            res_dict['res'] = 0
            return JsonResponse(res_dict)
        except:
            res_dict['res'] = 1
            return JsonResponse(res_dict)
    else:
        res_dict['res'] = 1
        return JsonResponse(res_dict)


@csrf_exempt
def product(request):
    if request.method == 'GET':
        res_dict = {}
        arr = {}
        pid = request.GET.get('pid')
        product = ProductList.objects.get(id=int(pid))
        res_dict['name'] = product.name
        res_dict['description'] = product.description
        res_dict['type'] = product.type
        res_dict['sellerUsername'] = product.seller
        res_dict['price'] = product.price
        res_dict['number'] = product.num
        res_dict['timeAndPlace'] = product.timeAndPlace
        res_dict['image'] = 'http://39.104.170.158:8000' + product.image.url
        arr['product'] = res_dict
        comments = Comments.objects.filter(pid=pid)
        commentslist = []
        for i in comments:
            a = {}
            student = Student.objects.get(name=i.username)
            a['image'] = 'http://39.104.170.158:8000' + student.image.url
            a['username'] = i.username
            a['time'] = i.time
            a['words'] = i.words
            commentslist.append(a)
        arr['comments'] = commentslist
        return JsonResponse(arr)
    elif request.method == 'POST':
        res_dict = {}
        data = json.loads(request.body)
        type = data.get('type')
        if type == 1:
            try:
                pid = data.get('pid')
                number = data.get('number')
                username = request.session.get('username')
                try:
                    shoppingbasket = ShoppingCart.objects.get(productID=pid, username=username)
                    product = ProductList.objects.get(id=pid)
                    shoppingbasket.num = min(shoppingbasket.num + number, product.num)
                    shoppingbasket.save()
                except:
                    shoppcart = ShoppingCart()
                    shoppcart.username = username
                    shoppcart.productID = pid
                    shoppcart.num = number
                    shoppcart.save()
                res_dict['res'] = 1
                return JsonResponse(res_dict)
            except:
                res_dict['res'] = 0
                return JsonResponse(res_dict)
        elif type == 2:
            time = data.get('time')
            words = data.get('words')
            pid = data.get('pid')
            username = request.session.get('username')
            comment = Comments()
            comment.time = time
            comment.pid = pid
            comment.username = username
            comment.words = words
            comment.save()
            comments = Comments.objects.filter(pid=pid).order_by('-id')
            commentslist = []
            for i in comments:
                a = {}
                student = Student.objects.get(name=i.username)
                a['image'] = 'http://39.104.170.158:8000' + student.image.url
                a['username'] = i.username
                a['time'] = i.time
                a['words'] = i.words
                commentslist.append(a)
            res_dict['comments'] = commentslist
            res_dict['res'] = 1
            return JsonResponse(res_dict)
        else:
            res_dict['res'] = 3;
            return JsonResponse(res_dict)


@csrf_exempt
def buyItNow(request):
    if request.method == 'GET':
        res_dict = {}
        pid = request.GET.get('pid')
        number = request.GET.get('number')
        username = request.session.get('username')
        p = ProductList.objects.get(id=int(pid))
        res_dict['name'] = p.name
        res_dict['sellerUsername'] = p.seller
        res_dict['type'] = p.type
        res_dict['price'] = p.price
        res_dict['number'] = number
        res_dict['description'] = p.description
        res_dict['total'] = float(p.price) * int(str(number))
        res_dict['timeAndPlace'] = p.timeAndPlace
        res_dict['sellerPhone'] = p.sellerPhone
        res_dict['image'] = 'http://39.104.170.158:8000' + p.image.url
        res_dict['sellerCode'] = 'http://39.104.170.158:8000' + p.sellerCode.url
        return JsonResponse(res_dict)
    elif request.method == 'POST':
        data = json.loads(request.body)
        res_dict = {}
        try:
            buyerPhone = data.get('buyerPhone')
            pid = data.get('pid')
            number = data.get('number')
            time = data.get('time')
            username = request.session.get('username')
            product = ProductList.objects.get(id=int(pid))
            order = OrderList()
            order.time = time
            if int(number) > product.num:
                res_dict['res'] = 0
                return JsonResponse(res_dict)
            order.number = number
            order.buyerPhone = buyerPhone
            order.buyerUsername = username
            order.sellerUsername = product.seller
            order.total = float(product.price) * int(str(number))
            order.isConfirmed = 0
            order.pid = pid
            order.save()
            ShoppingCart.objects.filter(productID=int(pid), username=username).delete()
            student = Student.objects.get(name=product.seller)
            student.buyNum = student.buyNum + 1
            student.save()
            product.num = product.num - int(str(number))
            product.save()
            res_dict['res'] = 1
            return JsonResponse(res_dict)
        except:
            res_dict['res'] = 0
            return JsonResponse(res_dict)


@csrf_exempt
def myCart(request):
    if request.method == 'GET':
        pid = request.GET.get('pid')
        res_dict = {}
        username = request.session.get('username')
        if pid != "":
            ShoppingCart.objects.filter(productID=int(pid)).filter(username=username).delete()
        username = request.session.get('username')
        shoppingcart = ShoppingCart.objects.filter(username=username)
        arr = []
        for i in shoppingcart:
            str = {}
            product = ProductList.objects.get(id=i.productID)
            str['image'] = 'http://39.104.170.158:8000' + product.image.url
            str['name'] = product.name
            str['description'] = product.description
            str['sellerUsername'] = product.seller
            str['price'] = product.price
            str['number'] = i.num
            str['pid'] = i.productID
            str['total'] = float(product.price) * int(i.num)
            arr.append(str)
        res_dict['cartProducts'] = arr
        return JsonResponse(res_dict)


# 自己写的第三部分
@csrf_exempt
def myOrder(request):
    res_dict = {}
    if request.method == 'GET':
        try:
            name = request.session.get('username')
            orderlist = OrderList.objects.filter(buyerUsername=name)
            orderlist2 = OrderList.objects.filter(sellerUsername=name)
        except:
            res_dict['res'] = 0
            return JsonResponse(res_dict)
        arr = []
        for i in orderlist:
            str = {}
            product = ProductList.objects.get(id=i.pid)
            str['image'] = 'http://39.104.170.158:8000' + product.image.url
            str['name'] = product.name
            str['total'] = i.total
            str['isConfirmed'] = i.isConfirmed
            str['number'] = i.number
            str['price'] = product.price
            str['point'] = i.point
            str['oid'] = i.id
            str['description'] = product.description
            str['sellerUsername'] = i.sellerUsername
            arr.append(str)
        res_dict['bought'] = arr
        arr = []
        for i in orderlist2:
            str = {}
            product = ProductList.objects.get(id=i.pid)
            str['image'] = 'http://39.104.170.158:8000' + product.image.url
            str['name'] = product.name
            str['isConfirmed'] = i.isConfirmed
            str['number'] = i.number
            str['price'] = product.price
            str['point'] = i.point
            str['oid'] = i.id
            str['total'] = i.total
            str['description'] = product.description
            str['buyerUsername'] = i.buyerUsername
            arr.append(str)
        res_dict['sold'] = arr
        return JsonResponse(res_dict)
    elif request.method == 'POST':
        data = json.loads(request.body)
        res_dict = {}
        try:
            point = data.get('point')
            oid = data.get('oid')
            order = OrderList.objects.get(id=int(oid))

            order.point = point
            order.isConfirmed = 1
            order.save()

            sellerUsername = order.sellerUsername
            orderlist = OrderList.objects.filter(sellerUsername=sellerUsername, isConfirmed=1)
            num = 0
            size = 0
            for i in orderlist:
                num += i.point
                size += 1
            seller = Student.objects.get(name=sellerUsername)
            num = num / size
            seller.point = num
            seller.save()

        except:
            res_dict['res'] = 0
            return JsonResponse(res_dict)

        res_dict['res'] = 1
        return JsonResponse(res_dict)


@csrf_exempt
def mySpace(request):
    if request.method == 'GET':
        type = request.GET.get('type')
        if type == "1":
            res_dict = {}
            username = request.session.get('username')
            student = Student.objects.get(name=username)
            res_dict['image'] = 'http://39.104.170.158:8000' + student.image.url
            res_dict['username'] = username
            res_dict['sex'] = student.sex
            res_dict['signature'] = student.signature
            res_dict['point'] = student.point
            res_dict['buyerNum'] = student.buyNum
            res_dict['phone'] = student.phone
            return JsonResponse(res_dict)
        elif type == "3":
            pid = request.GET.get('pid')

            if pid != "":
                ProductList.objects.get(id=int(pid)).delete()
            username = request.session.get('username')
            products = ProductList.objects.filter(seller=username).filter(num__gt=0)
            res_dict = {}
            arr = []
            for i in products:
                str = {}
                str['name'] = i.name
                str['image'] = 'http://39.104.170.158:8000' + i.image.url
                str['pid'] = i.id
                str['price'] = i.price
                arr.append(str)
            res_dict['products'] = arr
            return JsonResponse(res_dict)
        elif type == "4":
            nid = request.GET.get('nid')
            if nid != "":
                NeedList.objects.get(id=int(nid)).delete()
            username = request.session.get('username')
            needlist = NeedList.objects.filter(username=username)
            student = Student.objects.get(name=username)
            res_dict = {}
            arr = []
            for i in needlist:
                str = {}
                str['image'] = 'http://39.104.170.158:8000' + student.image.url
                str['username'] = username
                str['time'] = i.time
                str['nid'] = i.id
                str['description'] = i.description
                arr.append(str)
            res_dict['needs'] = arr

            return JsonResponse(res_dict)
        else:
            res_dict = {'res': 0}
            return JsonResponse(res_dict)
    elif request.method == 'POST':
        try:
            username = request.session.get('username')
            newImage = request.FILES.get('newImage')
            student = Student.objects.get(name=username)
            if newImage:
                student.image = newImage
            newPassword = request.POST.get('newPassword')
            if newPassword:
                student.password = newPassword
            newSex = request.POST.get('newSex')
            if newSex:
                student.sex = newSex
            newSignature = request.POST.get('newSignature')
            if newSignature:
                student.signature = newSignature
            newPhone = request.POST.get('newPhone')
            if newPhone:
                student.phone = newPhone
            student.save()
            res_dict = {'res': 1}
        except:
            res_dict = {'res': 0}
            return JsonResponse(res_dict)
        return JsonResponse(res_dict)


@csrf_exempt
def userInfo(request):
    if request.method == 'GET':
        type = request.GET.get('type')
        username = request.GET.get('username')
        res_dict = {}
        if type == "1":
            try:
                student = Student.objects.get(name=username)
                res_dict['image'] = 'http://39.104.170.158:8000' + student.image.url
                res_dict['username'] = username
                res_dict['sex'] = student.sex
                res_dict['signature'] = student.signature
                res_dict['point'] = student.point
                res_dict['buyerNum'] = student.buyNum

                res_dict['phone'] = student.phone
                res_dict['res'] = 1
            except:
                res_dict['res'] = 0
            return JsonResponse(res_dict)
        elif type == "2":
            products = ProductList.objects.filter(seller=username).filter(num__gt=0)
            arr = []
            for i in products:
                str = {}
                str['name'] = i.name
                str['image'] = 'http://39.104.170.158:8000' + i.image.url
                str['id'] = i.id
                str['price'] = i.price
                arr.append(str)
            res_dict['products'] = arr
            return JsonResponse(res_dict)
        elif type == "3":
            needs = NeedList.objects.filter(username=username)
            arr = []
            for i in needs:
                str = {}
                str['username'] = username
                str['description'] = i.description
                str['time'] = i.time
                arr.append(str)
            res_dict['needs'] = arr
            return JsonResponse(res_dict)


@csrf_exempt
def myMsg(request):
    if request.method == 'GET':
        res_dict = {}
        username = request.session.get('username')
        products = ProductList.objects.filter(seller=username).filter(num__gt=0)
        messages = []
        for i in products:

            comm = Comments.objects.filter(pid=i.id)
            if comm.count() == 0:
                continue
            a = {}
            a['pid'] = i.id
            a['image'] = 'http://39.104.170.158:8000' + i.image.url
            a['name'] = i.name
            comments = []
            for j in comm:
                b = {}
                b['username'] = j.username
                b['time'] = j.time
                b['words'] = j.words
                comments.append(b)
            a['comments'] = comments
            messages.append(a)
        res_dict['messages'] = messages
        return JsonResponse(res_dict)
